#!/usr/bin/python
# -*- coding: utf-8 -*-
import json, time, os
from urllib.request import urlopen
import sys
from urllib.parse import quote

dataName = "EstatePrice"

url = "http://v.juhe.cn/estate/query?"
appkey = "b47105a7cb941713688f542931553495"
dataDirectoryPath = "/home/xxx/Documents/Data/"+dataName+"/"
today = time.strftime('%Y-%m-%d', time.localtime(time.time()))

cityListPath = "../ConvinceCity/citylist.txt"
cityList = ""


def getEstatePrice(city):
    # if has existed,we shouldnt caught it again.
    if os.path.exists(dataDirectoryPath + today + "/" + today + "-" + city + ".json") == True:
        return

    # 如果API接口换了，改这里
    str = url + "city=" + city + "&key=" + appkey
    str = quote(str, safe="/=?:&")  # quote is great thing!

    response = urlopen(str).read().decode('utf-8')
    responseJson = json.loads(response)

    # check the resultcode,if resultcode equals 200 then create new file to save json
    if responseJson.get("resultcode") == "200":
        print(city + ":" + str)
        try:
            file = open(dataDirectoryPath + today + "/" + today + "-" + city + ".json", "w+")
            json.dump(responseJson, file, ensure_ascii=False)
        finally:
            file.close()
    else:
        print(city)


if __name__ == '__main__':
    if os.path.exists(dataDirectoryPath) ==False:
        os.mkdir(dataDirectoryPath)
    if os.path.exists(dataDirectoryPath + today) == False:
        os.mkdir(dataDirectoryPath + today)

    citylist = open('../ConvinceCity/citylist.txt')
    try:
        for city in citylist:
            getEstatePrice(city.replace("\n", ""))
    finally:
        citylist.close()
